package com.example.multithread;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    // Message的消息码
    private static final int START_NUM = 1;
    private static final int ADDING_NUM = 2;
    private static final int ENDING_NUM = 3;

    private TextView tvMsg;
    private ProgressBar progressBar;

    private ImageView ivImage;
    // 图片下载相关
    private static final String IMAGE_URL = "https://mmbiz.qpic.cn/mmbiz_jpg/3BfxhiacDTPDkxf2QoyhqCRibRk7eVRVz5460Lico5d4fgOU8IREwYCuUrP50ibPdOopxicic3390nQpA8lQlSN3lr2A/640?wx_fmt=jpeg";
    private static final int MSG_SHOW_PROGRESS = 1;
    private static final int MSG_SHOW_IMAGE = 2;


    private Thread numThread;
    private final Handler numHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case START_NUM:
                    progressBar.setVisibility(View.VISIBLE);
                    break;
                case ADDING_NUM:
                    progressBar.setProgress(msg.arg1);
                    tvMsg.setText("已完成" + msg.arg1 + "%");
                    break;
                case ENDING_NUM:
                    progressBar.setVisibility(View.GONE);
                    tvMsg.setText("计算结果：" + msg.arg1);
                    numHandler.removeCallbacks(numThread);
                    break;
            }
        }
    };
    private final Handler imageHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case MSG_SHOW_PROGRESS:
                    progressBar.setVisibility(View.VISIBLE);
                    break;
                case MSG_SHOW_IMAGE:
                    progressBar.setVisibility(View.GONE);
                    ivImage.setImageBitmap(((Bitmap) msg.obj));
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView() {
        tvMsg = findViewById(R.id.tv_msg);
        progressBar = findViewById(R.id.progress_bar);
        ivImage = findViewById(R.id.download_image);

        findViewById(R.id.btn_calculate).setOnClickListener(this);
        findViewById(R.id.btn_download_handler).setOnClickListener(this);
        findViewById(R.id.btn_download_async).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_calculate:
                numThread = new Thread(() -> {
                    int result = 0;
                    numHandler.sendEmptyMessage(START_NUM);

                    for (int i = 0; i < 101; i++) {
                        try {
                            Thread.sleep(100);
                            result += i;
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            return;
                        }
                        if (i % 5 == 0) {
                            Message msg = Message.obtain();
                            msg.what = ADDING_NUM;
                            msg.arg1 = i;
                            numHandler.sendMessage(msg);
                        }
                    }
                    Message msg = numHandler.obtainMessage();
                    msg.what = ENDING_NUM;
                    msg.arg1 = result;
                    numHandler.sendMessage(msg);
                });
                numThread.start();
                break;
            case R.id.btn_download_handler:
                new Thread(new ImageDownload(IMAGE_URL)).start();
                break;
            case R.id.btn_download_async:
                new ImageAsyncTask().execute(IMAGE_URL);
                break;
        }
    }

    private class ImageDownload implements Runnable {
        private final String imageUrl;

        private ImageDownload(String imageUrl) {
            this.imageUrl = imageUrl;
        }

        @Override
        public void run() {
            Message msg = Message.obtain();
            msg.what = MSG_SHOW_PROGRESS;
            imageHandler.sendMessage(msg);
            // imageHandler.obtainMessage(MSG_SHOW_PROGRESS).sendToTarget();

            try(InputStream is = new URL(imageUrl).openConnection().getInputStream()) {
                if (is != null) {
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    msg = Message.obtain();
                    msg.what = MSG_SHOW_IMAGE;
                    msg.obj = bitmap;
                    imageHandler.sendMessage(msg);
                    // imageHandler.obtainMessage(MSG_SHOW_IMAGE, bitmap).sendToTarget();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private class ImageAsyncTask extends AsyncTask<String, Bitmap, Bitmap> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            String imageUrl = params[0];

            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(imageUrl).openConnection();
                int length = connection.getContentLength();
                progressBar.setProgress(length);
                if (connection.getResponseCode() == 200) {
                    InputStream is = connection.getInputStream();
                    if (is != null) {
                        Bitmap bitmap = BitmapFactory.decodeStream(is);
                        is.close();
                        return bitmap;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if (bitmap != null) {
                ivImage.setImageBitmap(bitmap);
            }
            progressBar.setVisibility(View.GONE);
        }
    }
}

//                        int len = -1;
//                        int progress = 0;
//                        byte[] tmps = new byte[1024];
//                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
//                        while ((len = is.read(tmps)) != -1) {
//                            progress += len;
//                            progressBar.setProgress(progress);
//                            bos.write(tmps, 0, len);
//                        }
//                        bitmap = BitmapFactory.decodeByteArray(bos.toByteArray(), 0, bos.size());
